package org.example.controller;

import org.example.device.sync.DeviceStatusSyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 设备状态控制器
 * 提供设备状态同步和统计的REST API
 */
@RestController
@RequestMapping("/device-status")
@CrossOrigin(origins = "*")
public class DeviceStatusController {
    
    @Autowired
    private DeviceStatusSyncService deviceStatusSyncService;
    
    /**
     * 手动同步指定设备状态
     */
    @PostMapping("/{deviceId}/sync")
    public ResponseEntity<?> syncDeviceStatus(@PathVariable Long deviceId) {
        try {
            deviceStatusSyncService.syncDeviceStatus(deviceId);
            return ResponseEntity.ok(Map.of("message", "设备状态同步成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", "设备状态同步失败: " + e.getMessage()));
        }
    }
    
    /**
     * 批量同步设备状态
     */
    @PostMapping("/batch-sync")
    public ResponseEntity<?> syncDeviceStatusBatch(@RequestBody List<Long> deviceIds) {
        try {
            deviceStatusSyncService.syncDeviceStatusBatch(deviceIds);
            return ResponseEntity.ok(Map.of("message", "批量设备状态同步成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", "批量设备状态同步失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取设备状态统计
     */
    @GetMapping("/stats")
    public ResponseEntity<?> getDeviceStatusStats() {
        try {
            Map<String, Object> stats = deviceStatusSyncService.getDeviceStatusStats();
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", "获取设备状态统计失败: " + e.getMessage()));
        }
    }
}
